package com.mtiiot.util;

import java.io.*;
import java.math.BigDecimal;
import java.util.UUID;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;


public class Utils {
	private static Logger logger = LogManager.getLogger(Utils.class);
	// java 合并两个byte数组
	public static byte[] byteMerger(byte[] byte_1, byte[] byte_2) {
		byte[] byte_3 = new byte[byte_1.length + byte_2.length];
		System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
		System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
		return byte_3;
	}

	/**
	 * 获取堆栈字符串
	 * @param ex
	 * @return
	 */
	public static String getStackTrace(Throwable ex) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw, true);
		ex.printStackTrace(pw);
		return sw.getBuffer().toString();
	}
	
	public static void WriteStringToFile(String str,String filePath) throws IOException {
        //try {
            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(str);// 往已有的文件上添加字符串
            bw.close();
            fw.close();
        //} catch (Exception e) {
        //	logger.error(e.getMessage());
        //}
	}
	
	public static void WritebyteArrayToFile(byte[] byteArr,String filePath)  throws IOException {
			//try {
				FileOutputStream fos = new FileOutputStream(filePath);
				fos.write(byteArr) ;
				fos.flush();
				fos.close();  
			//} catch (Exception e) {
			//	logger.error(e.getMessage());
			//}
	}
	
	/** 
	 * Convert byte[] to hex string.这里我们可以将byte转换成int，然后利用Integer.toHexString(int)来转换成16进制字符串。 
	 * @param src byte[] data 
	 * @return hex string 
	 */     
	public static String bytesToHexString(byte[] src){  
	    StringBuilder stringBuilder = new StringBuilder("");  
	    if (src == null || src.length <= 0) {  
	        return null;  
	    }  
	    for (int i = 0; i < src.length; i++) {  
	        int v = src[i] & 0xFF;  
	        String hv = Integer.toHexString(v);  
	        if (hv.length() < 2) {  
	            stringBuilder.append(0);  
	        }  
	        stringBuilder.append(hv);  
	    }  
	    return stringBuilder.toString();  
	}  
	
	/** 
	 * Convert hex string to byte[] 
	 * @param hexString the hex string 
	 * @return byte[] 
	 */  
	public static byte[] hexStringToBytes(String hexString) {  
	    if (hexString == null || hexString.equals("")) {  
	        return null;  
	    }  
	    hexString = hexString.toUpperCase();  
	    int length = hexString.length() / 2;  
	    char[] hexChars = hexString.toCharArray();  
	    byte[] d = new byte[length];  
	    for (int i = 0; i < length; i++) {  
	        int pos = i * 2;  
	        d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
	    }  
	    return d;  
	} 
	
	/** 
	 * Convert char to byte 
	 * @param c char 
	 * @return byte 
	 */  
	 private static byte charToByte(char c) {  
	    return (byte) "0123456789ABCDEF".indexOf(c);  
	}  
	 
	/**
	 * 随机生成UUID
	 * 
	 * @return
	 */
	public static synchronized String getUUID() {
		UUID uuid = UUID.randomUUID();
		String str = uuid.toString();
		String uuidStr = str.replace("-", "");
		return uuidStr;
	}
	
	/**
	 * linux系统下获取当前可执行jar包对应的绝对路径
	 * @return
	 */
	public static String getCurrentRunableJarPath() {
		String path = System.getProperty("java.class.path");
		int firstIndex = path.lastIndexOf(System.getProperty("path.separator")) + 1;
		int lastIndex = path.lastIndexOf(File.separator) + 1;
		path = path.substring(firstIndex, lastIndex);
		return path;
	}
	
	
	/** 
     * byte(字节)根据长度转成kb(千字节)
     * 和mb(兆字节) 
     *  
     * @param bytes 
     * @return 
     */  
    public static float bytes2kb(long bytes) {  
        BigDecimal filesize = new BigDecimal(bytes);  
//        BigDecimal megabyte = new BigDecimal(1024 * 1024);  
//        float returnValue = filesize.divide(megabyte, 1, BigDecimal.ROUND_UP)  
//                .floatValue();  
//        if (returnValue > 1)  
//            return (returnValue + "MB");  
        BigDecimal kilobyte = new BigDecimal(1024);  
        float returnValue = filesize.divide(kilobyte, 1, BigDecimal.ROUND_UP)  
                .floatValue();  
        return returnValue;  
    }
}
